package com.powernode.money.service.impl;

import com.alibaba.dubbo.config.annotation.Service;
import com.powernode.money.constant.Constants;
import com.powernode.money.mapper.BidInfoMapper;
import com.powernode.money.model.BidInfo;
import com.powernode.money.service.BidInfoService;
import com.powernode.money.vo.TopLoanInfo;
import com.powernode.money.vo.TopRank;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ZSetOperations;
import org.springframework.data.redis.serializer.RedisSerializer;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.List;
import java.util.Set;
import java.util.concurrent.TimeUnit;

@Component
@Service(interfaceClass = BidInfoService.class,version = "1.0.0",timeout = 15000)
public class BidInfoServiceImpl implements BidInfoService {
    @Autowired
    private BidInfoMapper bidInfoMapper;

    @Autowired
    @Qualifier("redisTemplate")
    private RedisTemplate redisTemplate;

    @Override
    public double queryAllBidMoney() {
        return bidInfoMapper.selectAllBidMoney();
    }

    @Override
    public int executeInsertSelective(BidInfo record) {
        return bidInfoMapper.insertSelective(record);
    }

    @Override
    public List<TopRank> queryTopRank(int num) {
        return bidInfoMapper.selectTopRank(num);
    }

    @Override
    public List<TopLoanInfo> queryByLoanId(String loanId) {
        return bidInfoMapper.selectByLoanId(loanId);
    }

    @Override
    public List<TopLoanInfo> queryByUid(String uid) {
        return bidInfoMapper.selectByUid(uid);
    }

    @Override
    public List<TopRank> queryTopRankFromRedis(int num) {
        //字符串型的key的序列化器
        redisTemplate.setKeySerializer(RedisSerializer.string());
        List<TopRank> list = new ArrayList<>();
        //从redis反序获取ZSet的一个范围，并带Score
        Set<ZSetOperations.TypedTuple<String>> set = redisTemplate.opsForZSet().reverseRangeWithScores(Constants.INVEST_TOP, 0, num);
        if (set.isEmpty()){
            queryTopRank(num).forEach(x->{
                updateInvestTop(x.getPhone(),x.getMoney());
            });
            set = redisTemplate.opsForZSet().reverseRangeWithScores(Constants.INVEST_TOP, 0, num);
        }

        for(ZSetOperations.TypedTuple<String> typedTuple : set){
            TopRank topRank = new TopRank();
            topRank.setPhone(typedTuple.getValue());
            topRank.setMoney(typedTuple.getScore());
            list.add(topRank);
        }

        return list;
    }

    @Override
    public void updateInvestTop(String phone, double money) {
        //字符串型的key的序列化器
        redisTemplate.setKeySerializer(RedisSerializer.string());
        //保存数据
        redisTemplate.opsForZSet().incrementScore(Constants.INVEST_TOP, phone, money);
    }



}
